package com.epcs.controller.action;

import java.io.InputStream;
import java.io.StringBufferInputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;

import com.epcs.model.bo.CommentBO;
import com.epcs.model.bo.EventBO;
import com.epcs.model.bo.EventcategoryBO;
import com.epcs.model.bo.FollowingBO;
import com.epcs.model.bo.NotificationBO;
import com.epcs.model.dto.Account;
import com.epcs.model.dto.Comment;
import com.epcs.model.dto.Event;
import com.epcs.model.dto.Eventcategory;
import com.epcs.model.dto.Following;
import com.epcs.model.dto.Notification;
import com.epcs.util.EpcsDateTimeUtil;
import com.opensymphony.xwork2.ActionSupport;

public class FollowingEventAction extends ActionSupport implements
		SessionAware, ServletRequestAware {
	private String id;
	private String eventId;
	private String categoryId;
	private InputStream inputStream;
	private String eventIdForManagerment;
	private SessionMap<String, Object> sessionMap;
	private HttpServletRequest request;

	public String changeFollowing() {
		FollowingBO followBO = new FollowingBO();
		NotificationBO notifiBO = new NotificationBO();
		EventBO eventBO = new EventBO();
		// get user session
		Account account = (Account) sessionMap.get("USER_INFO");

		// kiem tra xem co login chua, neu khac null la login roi
		if (account != null) {
			//Nếu id= null nghĩa là chưa follow--> tạo following
			//Nếu id!=null là đã tồn tại--> xóa
			if ("".equals(id)) {
				// có eventID --> lấy event by ID				
				Event event = eventBO.getEvent(eventId);
				if(event != null){
					if("confirmed".equals(event.getStatus())){
						// dùng event đã lấy để tạo following và notification
						Following checkfollowing = followBO.loadFollowingEvent(account, eventId);
						if(checkfollowing == null){
							followBO.followingEventOrCategory(event, account);
							//tạo clone event cho event vừa đc follow
							String username = event.getAccount().getUsername();
							createEventForInvite(account, event, username);
							// lấy following đã tạo
							Following follow = followBO.loadFollowing(account, Integer.valueOf(eventId));
						
							// truyền following id về client
							inputStream = new StringBufferInputStream(String.valueOf(follow.getFollowingId()));
						}else{
							// truyền following id về client
							inputStream = new StringBufferInputStream("isExisted,"+checkfollowing.getFollowingId());
						}
					}else{
						inputStream = new StringBufferInputStream("cancelled");
					}
				}
				
				
				
			} else {
				Event event = eventBO.getEvent(eventId);
				if(event != null){
					if("confirmed".equals(event.getStatus())){
						
						Following follow = followBO.loadFollowingEventById(Integer.parseInt(id));
						List<Notification> listNotify = notifiBO.getNotificationByFollowing(follow);
						// Xóa list notification, xóa follow, và chuyển trạng thái event thành cancel
						if (listNotify != null) {
							for (int i = 0; i < listNotify.size(); i++) {
								notifiBO.deleteNotification(listNotify.get(i));
							}
						}
						followBO.deleteFollowingCategorybyAccount(follow); 
						
						//Duyệt list clone event và chuyển trạng thái sang 
						List<Event> cloneEventList = eventBO.getCloneEvent(account, event);
						if(cloneEventList!=null){
							for(int i = 0 ; i < cloneEventList.size(); i++){
								
								Event eventitem = cloneEventList.get(i);
								if("confirmed".equals(eventitem.getStatus())){
									eventitem.setDirty(true);
									eventitem.setSequence(eventitem.getSequence()+1);
									eventitem.setStatus("cancelled");
									eventBO.updateEvent(eventitem);
								}
								
							}
						}
					}else{
						inputStream = new StringBufferInputStream("cancelled");
					}
				}
			
				}
		} else {
			// neu chua login thi login
			inputStream = new StringBufferInputStream("Unauthorized");
		}

		return SUCCESS;
	}
	public String changeFollowingForManagement(){
		FollowingBO followBO = new FollowingBO();
		NotificationBO notifiBO = new NotificationBO();
		EventBO eventBO = new EventBO();
		Account account = (Account) sessionMap.get("USER_INFO");
		if (account != null) {
			// có eventID --> lấy event by ID				
			Event event = eventBO.getEvent(eventIdForManagerment);
			if(event != null){
				if("confirmed".equals(event.getStatus())){
					// dùng event đã lấy để tạo following và notification
					Following checkfollowing = followBO.loadFollowingEvent(account, eventIdForManagerment);
					if(checkfollowing == null){
						inputStream = new StringBufferInputStream("Fail");
					}else{
						
						List<Notification> listNotify = notifiBO.getNotificationByFollowing(checkfollowing);
						// Xóa list notification, xóa follow, và chuyển trạng thái event thành cancel
						if (listNotify != null) {
							for (int i = 0; i < listNotify.size(); i++) {
								notifiBO.deleteNotification(listNotify.get(i));
							}
						}
						followBO.deleteFollowingCategorybyAccount(checkfollowing); 
						//Duyệt list clone event và chuyển trạng thái sang 
						List<Event> cloneEventList = eventBO.getCloneEvent(account, event);
						if(cloneEventList!=null){
							for(int i = 0 ; i < cloneEventList.size(); i++){
								
								Event eventitem = cloneEventList.get(i);
								if("confirmed".equals(eventitem.getStatus())){
									eventitem.setDirty(true);
									eventitem.setSequence(eventitem.getSequence()+1);
									eventitem.setStatus("cancelled");
									eventBO.updateEvent(eventitem);
								}
								
							}
						}
					}
				}else{
					inputStream = new StringBufferInputStream("cancelled");
				}
			}
	
			
		} else {
			// neu chua login thi login
			inputStream = new StringBufferInputStream("Unauthorized");
		}
		return SUCCESS;
	}

	public String changeFollowingDetail() {
		FollowingBO followBO = new FollowingBO();
		EventBO newEventBO = new EventBO();
		Event eventDetail = newEventBO.getEvent(eventId);
		eventDetail.setStartTime(EpcsDateTimeUtil
				.convertToJSPDatetime(eventDetail.getStartTime()));
		eventDetail.setEndTime((EpcsDateTimeUtil
				.convertToJSPDatetime(eventDetail.getEndTime())));
		String result = "Success";
		// get user session
		Account account = (Account) sessionMap.get("USER_INFO");

		// kiem tra xem co login chua, neu khac null la login roi
		if (account != null) {
			Following following = followBO.loadFollowing(account,
					Integer.parseInt(eventId));
			if (following == null) {
				Following follow = new Following();
				follow.setAccount(account);
				follow.setIdOfFollow(Integer.parseInt(eventId));
				follow.setTypeOfFollow("event");
				followBO.insertFollowingEvent(follow);
			} else {
				followBO.deleteFollowingCategorybyAccount(following);
			}

			CommentBO newCommentBO = new CommentBO();
			List<Comment> commentList = newCommentBO
					.getAllCommentByEventId(eventDetail);
			Following follow1 = followBO.loadFollowing(account,
					Integer.parseInt(eventId));
			request.setAttribute("EVENT_DETAIL", eventDetail);
			request.setAttribute("COMMENT_LIST", commentList);
			request.setAttribute("FOLLOWING_EVENT", follow1);

		} else {
			// neu chua login thi login
			return "Unauthorized";
		}

		return result;
	}
	public Integer createEventForInvite(Account accountInvite, Event originalEvent, String organizer) {

		Event newEvent = new Event();
		EpcsDateTimeUtil dateUtil = new EpcsDateTimeUtil();
		
		newEvent.setReminderTime(originalEvent.getReminderTime());
		newEvent.setAccount(accountInvite);
		newEvent.setTitle(originalEvent.getTitle());
		if (originalEvent.getIsAllDayEvent()== true) {
			newEvent.setIsAllDayEvent(true);
			newEvent.setEndTime(originalEvent.getEndTime());
		} else {
			newEvent.setIsAllDayEvent(false);
			newEvent.setEndTime(originalEvent.getEndTime());
		}
		newEvent.setIsRecurrent(false);
		newEvent.setStartTime(originalEvent.getStartTime());
		// Add category vao Event
		// Lay category dua vao id cua category truyen vao
		EventcategoryBO newCatBO = new EventcategoryBO();
		Eventcategory newCat = newCatBO.getCatByID(originalEvent.getEventcategory().getEventCategoryId());
		newEvent.setEventcategory(newCat);
		newEvent.setLocation(originalEvent.getLocation());
		newEvent.setDescription(originalEvent.getDescription());
		newEvent.setStatus("confirmed");
		newEvent.setDirty(false);
		newEvent.setSequence(0);
		newEvent.setUpdated(EpcsDateTimeUtil.getCurrentIsoDateTime());
		newEvent.setVisibility("private");
		newEvent.setOrganizer(organizer);
		newEvent.setOriginalEvent(originalEvent);
		newEvent.setIsNotified(false);

		// -----------------------------------//
		// ---------------Tạo Event-----------//c
		EventBO newEventBO = new EventBO();
		// Trả về id của event mới
		int newEventId = newEventBO.createEvent(newEvent);

		return newEventId;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getEventId() {
		return eventId;
	}

	public void setEventId(String eventId) {
		this.eventId = eventId;
	}

	public String getCategoryId() {
		return categoryId;
	}

	public void setCategoryId(String categoryId) {
		this.categoryId = categoryId;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public String getEventIdForManagerment() {
		return eventIdForManagerment;
	}
	public void setEventIdForManagerment(String eventIdForManagerment) {
		this.eventIdForManagerment = eventIdForManagerment;
	}
	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;

	}

	@Override
	public void setSession(Map<String, Object> sessionMap) {
		this.sessionMap = (SessionMap<String, Object>) sessionMap;

	}
}
